package com.hkzhao.shixun.service.impl;
import com.hkzhao.shixun.common.utils.TokenUtil;
import com.hkzhao.shixun.dto.StatDto;
import com.hkzhao.shixun.mbg.mapper.StatMapper;
import com.hkzhao.shixun.mbg.model.Stat;
import com.hkzhao.shixun.mbg.model.StatExample;
import com.hkzhao.shixun.service.RedisService;
import com.hkzhao.shixun.service.StatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class StatServiceImpl implements StatService
{
    @Autowired
    private RedisService redisService;
    @Autowired(required=false)
    private StatMapper statMapper;
    @Override
    public Integer plus(String Activityid)
    {
        if (!redisService.hasKey(Activityid))
        {
            redisService.set(Activityid,1);
            return 1;
        }
        redisService.set(Activityid,1+(Integer)redisService.get(Activityid));
        return (Integer)redisService.get(Activityid);
    }
    @Override
    public void create(String Activityid)
    {
        if (!redisService.hasKey(Activityid))
            redisService.set(Activityid,0);
    }
    @Override
    public void remove(String Activityid)
    {
        if (redisService.hasKey(Activityid))
            redisService.del(Activityid);
        StatExample statExample=new StatExample();
        StatExample.Criteria r=statExample.createCriteria();r.andActivityidEqualTo(Activityid);
        statMapper.deleteByExample(statExample);
    }
    @Override
    public void transfertomysql(String Activityid)
    {
        Stat st=new Stat();
        st.setActivityid(Activityid);
        st.setDate(new Date());
        st.setVis(0);
        if (redisService.hasKey(Activityid))
        {
            st.setVis((Integer) redisService.get(Activityid));
            redisService.del(Activityid);
        }
        statMapper.insert(st);
    }
    @Override
    public List<StatDto> getstat(String Activityid, Date date)
    {
        StatExample statExample=new StatExample();
        StatExample.Criteria r=statExample.createCriteria();r.andActivityidIsNotNull();
        if (Activityid!=null) r.andActivityidEqualTo(Activityid);
        if (date!=null) r.andDateEqualTo(date);
        List<Stat> t=statMapper.selectByExample(statExample);
        if (t==null) return null;
        ArrayList<StatDto> res=new ArrayList<>();
        for (Stat x:t)
        {
            StatDto newele=new StatDto();
            newele.setActivityid(x.getActivityid());
            newele.setVis(x.getVis());
            newele.setDate(TokenUtil.formatSync8(x.getDate(),"yyyy-MM-dd"));
            res.add(newele);
        }
        return res;
    }
    @Override
    public Integer getnow(String Activityid)
    {
        Integer res=0;
        if (redisService.hasKey(Activityid))
            res=(Integer)redisService.get(Activityid);
        return res;
    }
}
